package com.xuliugen.ossdemo.qcloudclient;

import com.qcloud.cosapi.api.CosCloud;
import com.qcloud.cosapi.sign.Sign;
import com.xuliugen.ossdemo.common.constant.QcloudConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * 自己定义的七牛文件上传Client
 * Created by xuliugen on 16/5/22.
 */
public class QcloudClient {

    private static Properties props = new Properties();
    private static Logger log = LoggerFactory.getLogger(QcloudClient.class);

    static {
        try {
            props.load(QcloudClient.class.getResourceAsStream("/qcloud.properties"));
        } catch (IOException e) {
            log.error("加载配置文件失败", e);
        }
    }

    static int APP_ID = Integer.parseInt(props.getProperty("APP_ID"));
    static String SECRET_ID = props.getProperty("SECRET_ID");
    static String SECRET_KEY = props.getProperty("SECRET_KEY");
    static String bucketName = props.getProperty("bucketName");


    /**
     * 生成签名 多次有效签名
     * 签名中不绑定文件fileid，需要设置大于当前时间的有效期，有效期内此签名可多次使用，有效期最长可设置三个月。
     * @return
     */
    public static String appSignature() {
        long expired = System.currentTimeMillis() / 1000 + 2592000;
        return Sign.appSignature(APP_ID, SECRET_ID, SECRET_KEY, expired, bucketName);
    }

    /**
     * 单次签名
     * 签名中绑定文件fileid，有效期必须设置为0，此签名只可使用一次，且只能应用于被绑定的文件。
     * @param resourcePath 格式为"/myFloder/myCosFile.txt";
     * @return
     */
    public static String appSignatureOnce(String resourcePath) {
        return Sign.appSignatureOnce(APP_ID, SECRET_ID, SECRET_KEY, resourcePath, bucketName);
    }

    /**
     * 先获取bucketName下的成员，如果没有手动创建的话应该为空
     * 注意getFolderList获得的是目录的子成员信息
     * @return
     */
    public static String getFolderList() {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);

        String result = null;
        try {
            result = cos.getFolderList(bucketName, "/", QcloudConst.DIR_NUM, "", 0, CosCloud.FolderPattern.Both);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        cos.shutdown();
        System.out.println("getFolderList result: " + result);
        return result;
    }

    /**
     * 创造一个文件夹 格式为:"/folder1/"
     * @param remotePath
     * @return
     */
    public static String createFolder(String remotePath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);

        String result = null;
        try {
            result = cos.createFolder(bucketName, remotePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("createFolder result: " + result);
        return result;
    }

    /**
     * 自动判断文件的大小,已使用是否是分片的方式上传文件
     * @param remoteFolderPath 远程文件夹的名称
     * @param loaclPath        文件的本地路径
     * @return
     */
    public static String uploadFile(String remoteFolderPath, String loaclPath) {
        //获取文件输入流
        File f = new File(loaclPath);
        String result = null;
        if (f.exists() && f.isFile()) {
            long size = f.length();
            if (size <= 8 * 1024 * 1024) { //小于等于8M
                result = cosUploadFile(remoteFolderPath + getFileName(loaclPath), loaclPath);
            } else {
                result = sliceUploadFileParallel(remoteFolderPath + getFileName(loaclPath), loaclPath);
            }
        } else {
            System.out.println("file doesn't exist or is not a file");
        }
//        JSONObject retJson = new JSONObject(result);
//        int code = retJson.getInt(ResponseBodyKey.CODE); //文件上传返回码
        //如果错误 封装信息显示
//        return retJson.getString(ResponseBodyKey.MESSAGE); //文件上传返回信息

        return result;
    }

    /**
     * 上传一个长度为10个字节的文件
     * @param remotePath
     * @param loaclPath
     * @return
     */
    public static String cosUploadFile(String remotePath, String loaclPath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);

        String result = null;
        try {
            result = cos.uploadFile(bucketName, remotePath, loaclPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("uploadFile result:" + result);
        return result;
    }

    /**
     * 更新文件夹属性
     * @param remotePATH 远程remotePATH "/folder1/";
     * @param newPATH    新的PATH "demo test folder1"
     * @return
     */
    public static String updateFolder(String remotePATH, String newPATH) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;

        try {
            result = cos.updateFolder(bucketName, remotePATH, newPATH);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("updateFolder result: " + result);
        return result;
    }

    /**
     * 更新文件属性
     * @param remotePATH /len10.txt
     * @param newPATH    "demo test smallfile"
     * @return
     */
    public static String updateFile(String remotePATH, String newPATH) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);

        String result = null;
        try {
            result = cos.updateFile(bucketName, remotePATH, newPATH);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("updateFile result: " + result);
        return result;
    }

    /**
     * 获取目录列表
     * @param remotePath
     * @param dirNum
     * @param context
     * @return
     */
    public static String getFolderList(String remotePath, int dirNum, String context) {

        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;

        try {
            result = cos.getFolderList(bucketName, remotePath, dirNum, context, 0, CosCloud.FolderPattern.Both);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getFolderList result: " + result);
        return result;
    }

    /**
     * 获取文件属性
     * @param remotePath
     * @return
     */
    public static String getFileStat(String remotePath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;
        try {
            result = cos.getFileStat(bucketName, remotePath);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getFileStat result: " + result);
        return result;
    }

    /**
     * 获取文件夹属性
     * @param remotePath
     * @return
     */
    public static String getFolderStat(String remotePath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;
        try {
            result = cos.getFolderStat(bucketName, remotePath);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getFolderStat result: " + result);
        return result;
    }

    /**
     * 串行分片上传文件, 使用默认分片大小
     * @param remotePath
     * @param localPath
     * @return
     */
    public static String sliceUploadFile(String remotePath, String localPath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;
        try {
            result = cos.sliceUploadFile(bucketName, remotePath, localPath);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("sliceUploadFile result: " + result);
        return result;
    }

    /**
     * 串行分片上传文件, 使用分片大小512KB
     * @param remotePath
     * @param localPath
     * @return
     */
    public static String sliceUploadFileParallel(String remotePath, String localPath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;
        try {
            result = cos.sliceUploadFileParallel(bucketName, remotePath, localPath, 512 * 1024);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("para sliceUploadFile result: " + result);
        return result;
    }

    /**
     * 删除
     * @param remotePath
     * @return
     */
    public static String deleteFile(String remotePath) {
        CosCloud cos = new CosCloud(APP_ID, SECRET_ID, SECRET_KEY, 60);
        String result = null;
        try {
            result = cos.deleteFile(bucketName, remotePath);
            cos.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("deleteFile  result: " + result);
        return result;
    }


    /**
     * 根据本地文件的路径获取文件的名字
     * @param localPath 本地文件路径
     * @return 文件的名称
     */
    public static String getFileName(String localPath) {
        String[] result = localPath.split("\\/");
        return result[result.length - 1];
    }
}